//
//  MainScene.cpp
//  FingerBlock
//
//  Created by GaoFeng on 14-5-29.
//
//

#include "MainScene.h"
#include "UnitBlock.h"
USING_NS_CC;

CCScene* MainScene::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    MainScene *layer = MainScene::create();
    
    // add layer as a child to scene
    scene->addChild(layer);
    
    // return the scene
    return scene;
}

static CCDictionary s_dic;

void MainScene::registerWithTouchDispatcher(void)
{
    CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this, 0);
}

void MainScene::cleanBlocks()
{
    for (vector<CCNode *>::iterator itor = TheBlocks.begin(); itor != TheBlocks.end(); ++itor) {
        CCNode * pNode = *itor;
        UnitBlock * block = (UnitBlock *)pNode;
        if (block) {
            block->removeFromParent();
        }
    }
}

// on "init" you need to initialize your instance
bool MainScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    cleanBlocks();
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    MoveTime = 0.1f;
    setGameBlock(4, 5);
    
    FillBlock();
    
    setTouchEnabled(true);
    return true;
}

void MainScene::FillBlock(bool oneLine)
{
    srand(time(NULL));
    if (oneLine) {
        vector<CCNode *>::iterator itor = TheBlocks.end();
        itor--;
        CCNode * pNode = *itor;
        CCPoint startxy = CCPoint(0, pNode->getPositionY() + getBlockSize().height);
        int xlinemax = getBlock_H();
        int ylinemax = 1;
        
        for (int j = 0; j < ylinemax; ++j) {
            startxy.x = 0;
            for (int i = 0; i < xlinemax; ++i) {
                int res = rand()%2;
                CCLOG("Block color %d",res);
                UnitBlock * uBlock = UnitBlock::create();
                uBlock->setData(getBlockSize(), (res == 0)?ccWHITE:ccBLACK);
                uBlock->setPosition(startxy);
                startxy.x += getBlockSize().width;
                addChild(uBlock);
                TheBlocks.push_back(uBlock);
            }
            startxy.y += getBlockSize().height;
        }
    }
    else
    {
        CCPoint startxy = CCPoint(0, 0);
        int xlinemax = getBlock_H();
        int ylinemax = getBlock_V()+1;
        
        startMove = false;
        
        for (int j = 0; j < ylinemax; ++j) {
            startxy.x = 0;
            for (int i = 0; i < xlinemax; ++i) {
                int res = rand()%2;
                CCLOG("Block color %d",res);
                UnitBlock * uBlock = UnitBlock::create();
                uBlock->setData(getBlockSize(), (res == 0)?ccWHITE:ccBLACK);
                uBlock->setPosition(startxy);
                startxy.x += getBlockSize().width;
                addChild(uBlock);
                TheBlocks.push_back(uBlock);
            }
            startxy.y += getBlockSize().height;
        }
    }
}

void MainScene::setGameBlock(int h_count, int v_count)
{
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    setBlock_V(v_count);
    setBlock_H(h_count);

    setBlockSize(CCSize(winSize.width/h_count, winSize.height/v_count));
}

void MainScene::makeBlocksStop()
{
    CCLOG("ALL STOP");
    for (vector<CCNode *>::iterator itor = TheBlocks.begin(); itor != TheBlocks.end(); ++itor) {
        CCNode * pNode = *itor;
        pNode->stopAllActions();
    }
}

void MainScene::updateBlocks(float dt)
{
    if(!startMove)
    {
        startMove = true;
        makeBlocksMove();
        return;
    }
    
    vector<CCNode *>::iterator itor = TheBlocks.begin();
    CCNode * pNode = *itor;
    CCPoint pos = pNode->getPosition();
    if (pos.y + getBlockSize().height <= 0) {
        makeBlocksStop();
        for (int i = 0; i < getBlock_H(); ++i) {
            vector<CCNode *>::iterator s_itor = TheBlocks.begin();
            CCNode * s_pNode = *s_itor;
            TheBlocks.erase(s_itor);
            UnitBlock * uBlock = (UnitBlock *)s_pNode;
            uBlock->removeFromParent();
        }
        FillBlock(true);
        makeBlocksMove();
        return;
    }
}

void MainScene::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
    CCSetIterator iter = pTouches->begin();
    for (; iter != pTouches->end(); iter++)
    {
        CCTouch* pTouch = (CCTouch*)(*iter);
        CCNode * pNode = CCNode::create();
        CCPoint location = pTouch->getLocation();
        pNode->setPosition(location);
        
        addChild(pNode);
        s_dic.setObject(pNode, pTouch->getID());
    }
    schedule(schedule_selector(MainScene::updateBlocks));
}

void MainScene::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
    CCSetIterator iter = pTouches->begin();
    for (; iter != pTouches->end(); iter++)
    {
        CCTouch* pTouch = (CCTouch*)(*iter);
        CCNode* pNode = (CCNode*)s_dic.objectForKey(pTouch->getID());
        CCPoint location = pTouch->getLocation();
        pNode->setPosition(location);
    }
}

void MainScene::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
    CCSetIterator iter = pTouches->begin();
    for (; iter != pTouches->end(); iter++)
    {
        CCTouch* pTouch = (CCTouch*)(*iter);
        CCNode* pNode = (CCNode*)s_dic.objectForKey(pTouch->getID());
        removeChild(pNode);
        s_dic.removeObjectForKey(pTouch->getID());
    }
    startMove = false;
    unschedule(schedule_selector(MainScene::updateBlocks));
    makeBlocksStop();
}

void MainScene::makeBlocksMove()
{
    CCLOG("ALL MOVE");
    for (vector<CCNode *>::iterator itor = TheBlocks.begin(); itor != TheBlocks.end(); ++itor) {
        CCNode * pNode = *itor;
        if(pNode->numberOfRunningActions() == 0)
        {
            pNode->runAction(CCRepeatForever::create(CCMoveBy::create(MoveTime, ccp(0, -getBlockSize().height))));
        }
    }
}

void MainScene::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent)
{
    ccTouchesEnded(pTouches, pEvent);
}